package com.powernode.money.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.powernode.money.mapper.FinanceAccountMapper;
import com.powernode.money.mapper.UserMapper;
import com.powernode.money.model.FinanceAccount;
import com.powernode.money.model.User;
import com.powernode.money.service.UserService;
import com.powernode.money.vo.ApiResult;
import org.apache.commons.lang3.RandomStringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Service(interfaceClass = UserService.class, version = "1.0.0", timeout = 15000)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FinanceAccountMapper financeAccountMapper;

    @Value("${wxAppKey}")
    private String wxAppKey;

    @Autowired
    @Qualifier("stringRedisTemplate")
    private RedisTemplate stringRedisTemplate;

    @Override
    public int countUsers() {
        return userMapper.countUsers();
    }

    @Override
    public User queryByPhoneLoginPassword(String phone, String loginPassword) {
        return userMapper.selectByPhoneLoginPassword(phone, loginPassword);
    }

    @Override
    public User queryByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User queryByPhone(String phone) {
        return userMapper.selectByPhone(phone);
    }

    @Override
    public boolean sendSmscode(String phone) {
        //使用lang3生成6位的数字随机数
        String code = RandomStringUtils.randomNumeric(6);
        System.out.println(code);
        //封装短信请求
        String url = "https://way.jd.com/kaixintong/kaixintong";
        String content ="【凯信通】您的验证码是："+code;
        Map<String,String> params = new HashMap<>();
        params.put("mobile", phone);
        params.put("content", content);
        params.put("appkey", this.wxAppKey);
        try {
            //发出请求
//            String result = HttpClientUtils.doGet(url, params);
            //模拟返回结果
            String result = "{\n" +
                    "    \"code\": \"10000\",\n" +
                    "    \"charge\": false,\n" +
                    "    \"remain\": 0,\n" +
                    "    \"msg\": \"查询成功\",\n" +
                    "    \"result\": \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\" ?><returnsms>\\n <returnstatus>Success</returnstatus>\\n <message>ok</message>\\n <remainpoint>-7992467</remainpoint>\\n <taskID>210204053</taskID>\\n <successCounts>1</successCounts></returnsms>\",\n" +
                    "    \"requestId\": \"6705d9ba0f4d4a288fc4f723e6f285b3\"\n" +
                    "}";
            //解析json结果
            JSONObject jsonObject = JSONObject.parseObject(result);
            if("10000".equals(jsonObject.getString("code"))){
                String xml = jsonObject.getString("result");
                //解析xml结果
                Document document = DocumentHelper.parseText(xml);
                //RootElement 根元素
                Element rootElement = document.getRootElement();
                //获取returnstatus子元素中的文本
                Element returnstatusElement = rootElement.element("returnstatus");
                if("Success".equals(returnstatusElement.getText())){
                    //验证码存放到redis
                    stringRedisTemplate.opsForValue().set("sms-code-"+phone, code, 5, TimeUnit.MINUTES);
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean verifySmsCode(String phone, String code) {
        String redisCode= (String) stringRedisTemplate.opsForValue().get("sms-code-"+phone);
        if (redisCode==null){
            return false;
        }else if (code.equals(redisCode)){
            stringRedisTemplate.delete("sms-code-"+phone);
            return true;
        }else {
            return false;
        }

    }

    @Override
    public User register(String phone, String loginPassword) {
        //添加用户
        User user =new User();
        user.setPhone(phone);
        user.setLoginPassword(loginPassword);
        user.setAddTime(new Date());
        user.setLastLoginTime(new Date());
        //插入用户信息时，如何带回自增长id
        userMapper.insertSelective(user);

        //添加账号
        FinanceAccount financeAccount = new FinanceAccount();
        financeAccount.setUid(user.getId());
        financeAccount.setAvailableMoney(0d);
        financeAccountMapper.insert(financeAccount);
        return user;
    }

    @Override
    public int executeUpdateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public ApiResult verifyRealName(String realName, String cardNo) {
        String url = "https://way.jd.com/hl/idcardcheck";
        HashMap<String,String> params = new HashMap<>();
        params.put("cardNo", cardNo);
        params.put("realName", realName);
        params.put("appkey", wxAppKey);
        try {
//            String result = HttpClientUtils.doGet(url,params);
            //模拟调用结果
            String result = "{\n" +
                    "    \"code\": \"10000\",\n" +
                    "    \"charge\": false,\n" +
                    "    \"remain\": 0,\n" +
                    "    \"msg\": \"查询成功\",\n" +
                    "    \"result\": {\n" +
                    "        \"error_code\": 0,\n" +
                    "        \"reason\": \"成功\",\n" +
                    "        \"result\": {\n" +
                    "            \"realname\": \"张**\",\n" +
                    "            \"idcard\": \"123456************\",\n" +
                    "            \"isok\": true,\n" +
                    "            \"IdCardInfor\": {\n" +
                    "                \"province\": \"广东省\",\n" +
                    "                \"city\": \"广州市\",\n" +
                    "                \"district\": \"天河区\",\n" +
                    "                \"area\": \"广东省广州市天河区\",\n" +
                    "                \"sex\": \"男\",\n" +
                    "                \"birthday\": \"1990-8-12\"\n" +
                    "            }\n" +
                    "        }\n" +
                    "    },\n" +
                    "    \"requestId\": \"96933f51599e4a3b9c46519651a3e323\"\n" +
                    "}";
            //解析JSON结果
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(!"10000".equals(jsonObject.getString("code"))){
                return ApiResult.error("实名认证服务繁忙，请稍后重试");
            }
            boolean ok = jsonObject.getJSONObject("result").getJSONObject("result").getBoolean("isok");
            if(ok==true){
                return ApiResult.success();
            }else{
                return ApiResult.error("姓名与身份证号不匹配");
            }
        } catch (Exception e) {
            return ApiResult.error("实名认证服务繁忙，请稍后重试");
        }
    }
}
